import { StoryboardData, StoryboardScene } from '../../../types/document'
import { ExportData, ExportSceneData, ExportStatistics } from './types'

/**
 * 分镜数据转换器
 * 将分镜数据转换为导出格式
 */
export class StoryboardDataTransformer {
  
  /**
   * 转换分镜数据为导出格式
   */
  transform(storyboardData: StoryboardData, projectTitle: string = '未命名项目'): ExportData {
    const scenes = storyboardData.scenes || []
    const exportScenes = scenes.map(scene => this.transformScene(scene))
    const statistics = this.calculateStatistics(scenes)
    
    return {
      projectInfo: {
        title: projectTitle,
        description: storyboardData.description || '分镜脚本',
        createdAt: new Date(),
        totalScenes: scenes.length,
        totalDuration: statistics.totalDuration
      },
      scenes: exportScenes,
      statistics
    }
  }
  
  /**
   * 转换单个场景数据
   */
  private transformScene(scene: StoryboardScene): ExportSceneData {
    return {
      id: scene.id,
      order: scene.order,
      title: scene.title,
      description: scene.description || '',
      duration: scene.timing?.duration || scene.duration || 5,
      
      // 镜头信息
      shotType: this.getShotTypeDisplay(scene.shot?.type),
      cameraAngle: this.getCameraAngleDisplay(scene.shot?.angle),
      cameraMovement: this.getCameraMovementDisplay(scene.shot?.movement),
      
      // 场景信息
      location: scene.sceneLocation?.name || '未设置',
      locationType: this.getLocationTypeDisplay(scene.sceneLocation?.type),
      lighting: this.getLightingDisplay(scene.sceneLocation?.lighting),
      
      // 人物和道具
      characters: scene.elements?.characters?.map(c => c.name) || [],
      props: scene.elements?.props?.map(p => p.name) || [],
      
      // 制作信息
      priority: this.getPriorityDisplay(scene.production?.priority),
      complexity: this.getComplexityDisplay(scene.production?.complexity),
      notes: scene.description || '',
      
      // 缩略图 (待实现)
      thumbnail: undefined
    }
  }
  
  /**
   * 计算统计信息
   */
  calculateStatistics(scenes: StoryboardScene[]): ExportStatistics {
    if (scenes.length === 0) {
      return {
        totalScenes: 0,
        totalDuration: 0,
        averageDuration: 0,
        longestScene: null,
        shortestScene: null,
        scenesByType: {},
        locationCount: 0,
        characterCount: 0
      }
    }
    
    const durations = scenes.map(scene => scene.timing?.duration || scene.duration || 5)
    const totalDuration = durations.reduce((sum, duration) => sum + duration, 0)
    const averageDuration = totalDuration / scenes.length
    
    // 最长和最短场景
    let longestScene = { title: scenes[0].title, duration: durations[0] }
    let shortestScene = { title: scenes[0].title, duration: durations[0] }
    
    scenes.forEach((scene, index) => {
      const duration = durations[index]
      if (duration > longestScene.duration) {
        longestScene = { title: scene.title, duration }
      }
      if (duration < shortestScene.duration) {
        shortestScene = { title: scene.title, duration }
      }
    })
    
    // 按镜头类型统计
    const scenesByType: Record<string, number> = {}
    scenes.forEach(scene => {
      const shotType = this.getShotTypeDisplay(scene.shot?.type)
      scenesByType[shotType] = (scenesByType[shotType] || 0) + 1
    })
    
    // 地点和人物统计
    const locations = new Set(scenes.map(scene => scene.sceneLocation?.name).filter(Boolean))
    const characters = new Set(
      scenes.flatMap(scene => scene.elements?.characters?.map(c => c.name) || [])
    )
    
    return {
      totalScenes: scenes.length,
      totalDuration,
      averageDuration,
      longestScene,
      shortestScene,
      scenesByType,
      locationCount: locations.size,
      characterCount: characters.size
    }
  }
  
  /**
   * 生成场景缩略图
   */
  async generateThumbnails(scenes: StoryboardScene[]): Promise<string[]> {
    // TODO: 实现缩略图生成
    // 可以基于场景信息生成简单的预览图
    return scenes.map(() => '')
  }
  
  // 显示名称转换方法
  private getShotTypeDisplay(shotType: any): string {
    const typeMap: Record<string, string> = {
      'extreme_long': '极远景',
      'long': '远景', 
      'wide': '全景',
      'medium_wide': '中全景',
      'medium': '中景',
      'medium_close_up': '中近景',
      'close_up': '近景',
      'extreme_close_up': '特写',
      'detail': '细节'
    }
    return typeMap[shotType] || shotType || '中景'
  }
  
  private getCameraAngleDisplay(angle: any): string {
    const angleMap: Record<string, string> = {
      'bird_eye': '鸟瞰',
      'high': '俯视',
      'slightly_high': '微俯',
      'eye_level': '平视',
      'slightly_low': '微仰',
      'low': '仰视',
      'worm_eye': '虫视'
    }
    return angleMap[angle] || angle || '平视'
  }
  
  private getCameraMovementDisplay(movement: any): string {
    if (!movement) return '静止'
    
    const movementMap: Record<string, string> = {
      'static': '静止',
      'pan_left': '左摇',
      'pan_right': '右摇', 
      'tilt_up': '上摇',
      'tilt_down': '下摇',
      'zoom_in': '推镜',
      'zoom_out': '拉镜',
      'dolly_in': '推轨',
      'dolly_out': '拉轨',
      'track_left': '左移',
      'track_right': '右移'
    }
    return movementMap[movement] || movement
  }
  
  private getLocationTypeDisplay(type: any): string {
    const typeMap: Record<string, string> = {
      'interior': '内景',
      'exterior': '外景',
      'studio': '演播室'
    }
    return typeMap[type] || type || '内景'
  }
  
  private getLightingDisplay(lighting: any): string {
    const lightingMap: Record<string, string> = {
      'natural_day': '自然光(日)',
      'natural_night': '自然光(夜)',
      'natural_dawn': '自然光(晨)',
      'natural_dusk': '自然光(昏)',
      'artificial_bright': '人工光(亮)',
      'artificial_dim': '人工光(暗)',
      'mixed': '混合光'
    }
    return lightingMap[lighting] || lighting || '自然光(日)'
  }
  
  private getPriorityDisplay(priority: any): string {
    const priorityMap: Record<string, string> = {
      'low': '低',
      'normal': '普通', 
      'high': '高',
      'urgent': '紧急'
    }
    return priorityMap[priority] || priority || '普通'
  }
  
  private getComplexityDisplay(complexity: any): string {
    const complexityMap: Record<string, string> = {
      'simple': '简单',
      'medium': '中等',
      'complex': '复杂'
    }
    return complexityMap[complexity] || complexity || '简单'
  }
}